import { defineStore } from 'pinia';

export const useUserStore = defineStore('user', {
  persist: true, // 启用持久化存储
  state: () => ({
    user: null,
    isAuthenticated: false
  }),
  actions: {
    // 登录时更新用户信息和认证状态
    login(userData) {
      this.user = userData;
      this.isAuthenticated = true;
      // 将JWT令牌存储到localStorage，供axios拦截器使用
      if (userData.token) {
        localStorage.setItem('token', userData.token);
      }
    },

    // 退出时清除用户信息和认证状态
    logout() {
      this.user = null;
      this.isAuthenticated = false;
      // 清除localStorage中的token
      localStorage.removeItem('token');
    }
  },
  getters: {
    // 获取用户名
    username: (state) => {
      return state.user?.userName || '未登录';
    }
  }
});